package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void deleteById(Long id) {
        //先在dish表中查询该菜品是否属于该category分类
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //判断dish表中的category_id和接受的参数id是否一直
        wrapper.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(wrapper);
        //对count1进行判断  如果>0,证明有数据,则不能删除
        if (count1 > 0) {
            //因为操作失误,用到自定义异常类 抛出信息
            throw new CustomException("当前分类下有菜品,不能删除");
        }

        //在setmeal表中查询该分类是否属于category分类
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(queryWrapper);
        log.info("count2:{}",count2);
        //对count2进行判断  如果>0,证明有数据,则不能删除
        if (count2 > 0) {
            //因为操作失误,用到自定义异常类 抛出信息
            throw new CustomException("当前分类下有套餐,不能删除");
        }
        //正常删除的情况
        super.removeById(id);
    }
}
